<template>
  <div class="app-container">
    <!-- 头部操作栏 -->
    <div class="header">
      <h2>医院科室管理</h2>
      <div class="header-actions">
        <el-radio-group v-model="currentLevel" @change="handleLevelChange">
          <el-radio-button :label="0">全部</el-radio-button>
          <el-radio-button :label="1">一级科室</el-radio-button>
          <el-radio-button :label="2">二级科室</el-radio-button>
        </el-radio-group>
        <el-button type="primary" @click="handleAddDepartment">
          <el-icon><Plus /></el-icon>
          新增科室
        </el-button>
      </div>
    </div>

    <!-- 科室表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
      border
      row-key="id"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="科室名称" width="180" />
      <el-table-column prop="level" label="级别" width="100">
        <template #default="{ row }">
          {{ row.levelId === 1 ? '一级' : '二级' }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="120">
        <template #default="{ row }">
          <el-switch
            v-model="row.status"
            :active-value="true"
            :inactive-value="false"
            active-text="显示"
            inactive-text="隐藏"
            @change="handleStatusChange(row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" />
      <el-table-column prop="creator" label="上传人" width="120" />
      <el-table-column prop="createTime" label="添加时间" width="180">
        <template #default="{ row }">
          {{ formatDateTime(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="addSubordinate(row)">
            新增下级
          </el-button>
          <el-button type="success" size="small" @click="viewSubordinates(row)">
            查看下级
          </el-button>
          <el-button type="warning" size="small" @click="editItem(row)">
            编辑
          </el-button>
          <el-button type="danger" size="small" @click="deleteItem(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 底部操作栏 -->
    <div class="footer">
      <div class="batch-actions">
        <el-button @click="toggleAllSelection">全选/取消全选</el-button>
        <el-button type="danger" @click="batchDelete">批量删除</el-button>
      </div>
      <el-pagination
        v-model:currentPage="currentPage"
        :page-size="pageSize"
        :total="total"
        layout="total, prev, pager, next"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增科室' : '编辑科室'"
      width="600px"
      @closed="resetForm"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="科室名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入科室名称" />
        </el-form-item>
        <el-form-item label="上级科室">
          <el-select
            v-model="form.parentId"
            placeholder="请选择上级科室"
            clearable
            :disabled="!!form.parentLevel"
          >
            <el-option
              v-for="item in parentOptions"
              :key="item.id"
              :label="`${item.name}（${item.level}级）`"
              :value="item.id"
            />
          </el-select>
          <div class="form-tip">
            {{
              form.parentLevel ? '当前为下级科室添加' : '不选择默认为顶级科室'
            }}
          </div>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="form.remark"
            type="textarea"
            :maxlength="140"
            show-word-limit
            placeholder="请输入备注"
            rows="4"
          />
        </el-form-item>
        <el-form-item label="是否显示" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="true">显示</el-radio>
            <el-radio :label="false">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, nextTick, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
import { Plus } from '@element-plus/icons-vue';
import { useCounterStore } from '@/stores/counter';
const store = useCounterStore();
// 表格数据
const tableData = ref([]);
const loading = ref(false);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 对话框相关
const dialogVisible = ref(false);
const dialogType = ref('add'); // add/edit
const formRef = ref(null);
const form = ref(initFormData());
const editingId = ref(null);

// 表单验证规则
const rules = ref({
  name: [
    { required: true, message: '请输入科室名称', trigger: 'blur' },
    { max: 50, message: '长度不能超过50个字符', trigger: 'blur' }
  ],
  status: [{ required: true, message: '请选择显示状态', trigger: 'change' }]
});

// 级别筛选
const currentLevel = ref(0);
const currentDepartmentId = ref(null);

// 初始化表单数据
function initFormData() {
  return {
    id: null,
    name: '',
    parentId: null,
    parentLevel: null,
    level: 1,
    status: true,
    remark: ''
  };
}

// 获取科室列表数据
const fetchDepartmentList = async () => {
  loading.value = true;
  try {
    const params = {};
    if (currentLevel.value > 0) {
      params.LevelId = currentLevel.value;
    }
    if (currentDepartmentId.value) {
      params.DepartmentId = currentDepartmentId.value;
    }

    console.log('Fetching departments with params:', params); // 添加日志

    const response = await axios.get(
      'http://localhost:5223/api/HospitalDepartment/HospitalDepartQuery',
      { params }
    );
    if (response.data.code === 210) {
      tableData.value = response.data.list.map((item) => ({
        id: item.departmentId,
        name: item.departmentName,
        level: item.level,
        levelId: item.levelId,
        status: item.status === 1,
        remark: item.remarks,
        creator: item.uploader,
        createTime: item.createTime,
        parentId: item.parentId
      }));
      total.value = response.data.totalCount;
    } else {
      ElMessage.error(response.data.msg || '获取数据失败');
    }
  } catch (error) {
    console.error('获取科室列表失败:', error);
    ElMessage.error('获取科室列表失败');
  } finally {
    loading.value = false;
  }
};

// 上级科室选项（过滤当前编辑项）
const parentOptions = computed(() => {
  return tableData.value.filter(
    (item) =>
      item.id !== editingId.value &&
      (dialogType.value === 'add' ? true : item.id !== form.value.parentId)
  );
});

// 打开新增对话框
const handleAddDepartment = () => {
  dialogType.value = 'add';
  dialogVisible.value = true;
  nextTick(() => {
    if (formRef.value) formRef.value.clearValidate();
  });
};

// 新增下级
const addSubordinate = (row) => {
  form.value = {
    ...initFormData(),
    parentId: row.id,
    parentLevel: row.level
  };
  dialogType.value = 'add';
  dialogVisible.value = true;
};

// 打开编辑对话框
const editItem = (row) => {
  dialogType.value = 'edit';
  editingId.value = row.id;
  form.value = {
    id: row.id,
    name: row.name,
    parentId: row.parentId,
    level: row.level,
    status: row.status,
    remark: row.remark
  };
  dialogVisible.value = true;
};

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate();

    const payload = {
      departmentName: form.value.name,
      level: form.value.level.toString(),
      status: form.value.status ? 1 : 0,
      remarks: form.value.remark,
      uploader: store.ccstore.nickName,
      createName: store.ccstore.nickName,
      parentId: form.value.parentId || 0,
      levelId: form.value.parentLevel || 0
    };

    if (dialogType.value === 'add') {
      // 新增科室
      const response = await axios.post(
        'http://localhost:5260/api/HospitalDepartment/DepartmentCreate',
        payload
      );

      if (response.data.code === 212) {
        ElMessage.success('新增成功');
        dialogVisible.value = false;
        // 重新加载数据
        fetchDepartmentList();
      } else {
        ElMessage.error(response.data.msg || '新增失败');
      }
    } else {
      // 修改科室
      const updatePayload = {
        ...payload,
        departmentId: form.value.id
      };
      const response = await axios.post(
        'http://localhost:5260/api/HospitalDepartment/DepartmentUpdate',
        updatePayload
      );

      if (response.data.code === 206) {
        ElMessage.success('修改成功');
        dialogVisible.value = false;
        fetchDepartmentList();
      } else {
        ElMessage.error(response.data.msg || '修改失败');
      }
    }
  } catch (error) {
    console.error('提交失败:', error);
    ElMessage.error('请检查表单内容');
  }
};

// 重置表单
const resetForm = () => {
  form.value = initFormData();
  editingId.value = null;
};

// 删除单个
const deleteItem = (row) => {
  ElMessageBox.confirm(`确定删除【${row.name}】及其所有下级科室吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        const response = await axios.post(
          'http://localhost:5260/api/HospitalDepartment/DepartmentDelete',
          {
            departmentId: row.id
          }
        );

        if (response.data.code === 204) {
          ElMessage.success('删除成功');
          // 重新加载数据
          fetchDepartmentList();
        } else {
          ElMessage.error(response.data.msg || '删除失败');
        }
      } catch (error) {
        console.error('删除失败:', error);
        ElMessage.error('删除失败，请重试');
      }
    })
    .catch(() => {
      // 用户取消删除操作
    });
};

// 批量删除
const batchDelete = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的科室');
    return;
  }

  ElMessageBox.confirm(
    `确定删除选中的${multipleSelection.value.length}个科室吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        // 逐个删除选中的科室
        const deletePromises = multipleSelection.value.map((item) =>
          axios.post(
            'http://localhost:5260/api/HospitalDepartment/DepartmentDelete',
            {
              departmentId: item.id
            }
          )
        );

        const results = await Promise.all(deletePromises);
        const successCount = results.filter(
          (res) => res.data.code === 204
        ).length;

        if (successCount > 0) {
          ElMessage.success(`成功删除${successCount}个科室`);
          // 重新加载数据
          fetchDepartmentList();
        } else {
          ElMessage.error('删除失败');
        }
      } catch (error) {
        console.error('批量删除失败:', error);
        ElMessage.error('批量删除失败，请重试');
      }
    })
    .catch(() => {
      // 用户取消删除操作
    });
};

// 多选操作
const multipleSelection = ref([]);
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

const toggleAllSelection = () => {
  // 实际实现需要使用表格实例的toggleAllSelection方法
  // 这里需要添加表格ref并实现具体逻辑
};

// 监听分页变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchDepartmentList();
};

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '';
  const date = new Date(dateTimeStr);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  });
};

// 处理状态变更
const handleStatusChange = async (row) => {
  try {
    // TODO: 调用API更新状态
    // const response = await axios.post('/api/HospitalDepartment/UpdateStatus', {
    //   departmentId: row.id,
    //   status: row.status ? 1 : 0
    // })
    ElMessage.success('状态更新成功');
  } catch (error) {
    console.error('更新状态失败:', error);
    ElMessage.error('更新状态失败');
    // 恢复原状态
    row.status = !row.status;
  }
};

// 处理级别变更
const handleLevelChange = (level) => {
  currentLevel.value = level;
  currentDepartmentId.value = null; // 重置当前选中的科室ID
  fetchDepartmentList();
};

// 查看下级
const viewSubordinates = (row) => {
  currentDepartmentId.value = row.id;
  currentLevel.value = 2;
  fetchDepartmentList();
};

// 返回上级
const backToParent = () => {
  currentDepartmentId.value = null;
  currentLevel.value = 0; // 重置为全部
  fetchDepartmentList();
};

// 初始化加载数据
onMounted(() => {
  fetchDepartmentList();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
  background: #f5f7fa;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 20px;
  align-items: center;
}

.footer {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-table {
  margin-top: 20px;
  background: white;
}

.batch-actions {
  display: flex;
  gap: 10px;
}

.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.el-select {
  width: 100%;
}
</style>
